import { Form, Input, message, Modal } from "antd";
import React, { useEffect } from "react";
import { UserApp, UserAppDetail, UserAppTree } from "../../../serve/interface";
import { validteUserAppTree } from "../../../serve/validators/tree";
import { apis } from "../../apis";

export interface ModalTreeNodeProps {
    btn: React.ReactNode;
    app: UserApp;
    item_id?: number;
    parentId?: number;
    detail: UserAppDetail;
    onChange: (data: { item: UserAppTree, detail: UserAppDetail }) => void;
}

export const ModalTreeNode: React.FC<ModalTreeNodeProps> = (props) => {
    const { app, btn, item_id, detail, parentId, onChange } = props;
    const [open, setOpen] = React.useState(false);
    const [form] = Form.useForm<UserAppTree>();
    const item = detail.tree.find(item => item.id === item_id)
    const isEdit = item ? true : false;
    const onFinish = async () => {
        const values = await form.validateFields()
        const res = await apis.save_dir({
            app_id: app.id,
            item: { ...item, ...values, parentId },
        })
        if (res.success) {
            onChange && onChange(res.data)
            setOpen(false)
        } else {
            message.error(res.message)
        }
    }

    useEffect(() => {
        if (open) {
            if (item) {
                form.setFieldsValue(item)
            } else {
                form.resetFields()
            }
        }
    }, [item, open])
    return (
        <>
            <span onClick={() => setOpen(true)}>{btn}</span>
            <Modal open={open} title={isEdit ? "修改基本信息" : "新建文档"} onOk={onFinish} onCancel={() => setOpen(false)}>
                <Form form={form} onFinish={onFinish} labelCol={{ span: 4 }} className="pt-4">
                    <Form.Item name="title" label="文档名称" rules={[
                        { required: true, message: "请输入名称" },
                        { min: 2, message: "名称至少2个字符" },
                        {
                            validator: (_, value) => {
                                const error = validteUserAppTree({ title: value, parentId, id: item_id }, detail)
                                if (error) {
                                    return Promise.reject(error)
                                } else {
                                    return Promise.resolve()
                                }
                            }
                        }
                    ]}>
                        <Input placeholder="请输入文档名称" />
                    </Form.Item>
                    <Form.Item label="文档描述" name="description">
                        <Input.TextArea rows={5} placeholder="请输入文档描述" />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}